﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Photoshop fillmode
    /// </summary>
    public class FarbigAbwedeln : BaseImageFilter, ITwoSourceFilter
    {
        /// <summary>
        /// 
        /// </summary>
        public FarbigAbwedeln()
        {
        }

        internal FarbigAbwedeln(FarbigAbwedeln _farbigAbwedeln)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            Process((UnsafeBitmap)_bitmap.Clone(), _bitmap);
            return _bitmap;
        }

        #region ITwoSourceFilter Members

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmapSource"></param>
        /// <param name="_bitmapDest"></param>
        /// <returns></returns>
        public UnsafeBitmap Process(UnsafeBitmap _bitmapSource, UnsafeBitmap _bitmapDest)
        {
            UnsafeBitmap bitmapSource = _bitmapSource;
            UnsafeBitmap bitmapDest = _bitmapDest;

            Color colorSource = Color.Transparent;
            Color colorDest = Color.Transparent;

            int y = 0;
            int x = 0;

            int nHeight = bitmapSource.Height;
            int nWidth = bitmapSource.Width;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    colorSource = bitmapSource.GetPixel(x, y);
                    colorDest = bitmapDest.GetPixel(x, y);

                    float nRSource = colorSource.R;
                    float nGSource = colorSource.G;
                    float nBSource = colorSource.B;

                    float nRedDiv = 255 - nRSource; if (nRedDiv == 0) nRedDiv = 1;
                    float nGreenDiv = 255 - nGSource; if (nGreenDiv == 0) nGreenDiv = 1;
                    float nBlueDiv = 255 - nBSource; if (nBlueDiv == 0) nBlueDiv = 1;
                    nRSource = colorDest.R / nRedDiv;
                    nGSource = colorDest.G / nGreenDiv;
                    nBSource = colorDest.B / nBlueDiv;
                    colorDest = Color.FromArgb((int)nRSource, (int)nGSource, (int)nBSource);
                    bitmapDest.SetPixel(x, y, colorDest);
                }
            }
            _bitmapDest.Dispose();
            _bitmapSource.Dispose();

            return _bitmapDest;
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new FarbigAbwedeln(this);
        }
    }
}
